package cookie;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * 查看cookie。
 */
public class GetCookieHeader extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        String params = req.getParameter("header");
        if (params != null && params.length() > 0)
            getCookieHeader(req, resp);
        else
            getCookie(req, resp);
    }

    public void getCookieHeader(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.getWriter().println("通过请求头获得cookie");
        String cookies = req.getHeader("Cookie");
        resp.getWriter().println(cookies);
    }

    public void getCookie(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.getWriter().println("通过便捷方法获得cookie");
        Cookie[] cookies = req.getCookies();
        for (Cookie cookie : cookies) {
            resp.getWriter().println(cookie.getName() + "=" + cookie.getValue());
        }
    }
}
